<template>
  <view class="container">
    <Loading :show="isLoading" />
    <!-- 收藏列表 -->
    <view class="favorite-list">
      
      <view v-if="favoriteList.length === 0 && !isLoading" class="empty-state">
        <image src="/static/empty-favorite.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无收藏商品</text>
      </view>

      <view v-else class="product-grid">
        <view v-for="item in favoriteList" :key="item.id" class="product-item">
          <view class="product-card">
            <image 
              :src="item.productImage || '/static/default-product.png'" 
              mode="aspectFill" 
              class="product-image" 
              @click="goToDetail(item.productId)"
              @error="handleImageError"
            ></image>
            <view class="product-info">
              <text class="product-name">{{ item.productName || '商品名称' }}</text>
              <view class="product-price-row">
                <text class="product-price">¥{{ item.productPrice || '0.00' }}</text>
                <text class="product-original-price" v-if="item.originalPrice && item.originalPrice > item.productPrice">¥{{ item.originalPrice }}</text>
              </view>
              <view class="product-actions">
                <button class="remove-favorite-btn" @click="removeFavorite(item)">取消收藏</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getFavoriteList, deleteFavorite } from '@/api/product/favorite';
import { getProductDetail } from '@/api/product';
import Loading from '@/components/Loading.vue';

interface FavoriteItem {
  id: number;
  productId: number;
  productName: string;
  productPrice: number;
  productImage: string;
  originalPrice?: number;
  description?: string;
}

const favoriteList = ref<FavoriteItem[]>([]);
const isLoading = ref(false);

// 获取收藏列表
const fetchFavoriteList = async () => {
  try {
    isLoading.value = true;
    
    const res = await getFavoriteList();
    
    if (res.rows && res.rows.length > 0) {
      // 获取每个收藏商品的详细信息
      const favoritesWithProductInfo = await Promise.all(
        res.rows.map(async (favorite: any) => {
          try {
            const productRes = await getProductDetail(favorite.productId);
            const product = productRes.data;
            
            return {
              id: favorite.id,
              productId: favorite.productId,
              productName: product.name,
              productPrice: product.price,
              productImage: product.productDetail?.mainImage || product.mainImage,
              originalPrice: product.originalPrice,
              description: product.productDetail?.description || product.description
            };
          } catch (error) {
            // 如果获取商品详情失败，使用收藏记录中的基本信息
            return {
              id: favorite.id,
              productId: favorite.productId,
              productName: '商品信息获取失败',
              productPrice: 0,
              productImage: '/static/default-product.png',
              originalPrice: 0,
              description: ''
            };
          }
        })
      );
      
      favoriteList.value = favoritesWithProductInfo;
    } else {
      favoriteList.value = [];
    }
  } catch (error) {
    uni.showToast({
      title: '获取收藏列表失败',
      icon: 'none'
    });
    favoriteList.value = [];
  } finally {
    isLoading.value = false;
  }
};

// 跳转到商品详情
const goToDetail = (productId: number) => {
  uni.navigateTo({
    url: `/pages/product/detail?id=${productId}`
  });
};

// 取消收藏
const removeFavorite = (item: FavoriteItem) => {
  uni.showModal({
    title: '提示',
    content: '确定取消收藏该商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteFavorite(item.id);
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          });
          // 重新获取收藏列表
          await fetchFavoriteList();
        } catch (error) {
          uni.showToast({
            title: '取消失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 页面加载时获取收藏列表
onMounted(() => {
  fetchFavoriteList();
});

// 页面显示时刷新数据
onShow(() => {
  fetchFavoriteList();
});

// 处理图片加载错误
const handleImageError = (e: Event) => {
  console.error('图片加载错误:', e);
  // 可以添加一些默认图片或错误处理逻辑
};
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 10px;
}

.favorite-list {
  padding: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 10px;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.product-item {
  background-color: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-card {
  display: flex;
  flex-direction: column;
}

.product-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.product-info {
  padding: 10px;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-price-row {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 8px;
}

.product-price {
  font-size: 16px;
  color: #ff6b6b;
  font-weight: bold;
}

.product-original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.product-actions {
  display: flex;
  gap: 8px;
}

.add-cart-btn,
.remove-favorite-btn {
  flex: 1;
  font-size: 12px;
  padding: 4px 0;
  border-radius: 15px;
  border: none;
}

.add-cart-btn {
  background-color: #ff6b6b;
  color: #ffffff;
}

.remove-favorite-btn {
  background-color: #f0f0f0;
  color: #666;
}

.debug-info {
  background-color: #f0f0f0;
  padding: 10rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #666;
}

.debug-info text {
  display: block;
  margin-bottom: 5rpx;
}
</style> 